/**
 * 执行程序并返回promise
 * @param {string} command 执行程序名称
 * @param {Array<string>} [args] 执行程序传入的参数
 * @param {Object} [options] 配置项 { cwd: process.cwd() }
 */
exports.spawnSync = (command, args, options) => {
  return new Promise((resolve, reject) => {
    const proc = require('child_process').spawn(command, args, options)
    proc.stdout.pipe(process.stdout)
    proc.stderr.pipe(process.stderr)
    proc.on('error', reject)
    proc.on('close', resolve)
  })
}

/**
 * 下载依赖
 * @param {string} cwd process.cwd()
 */
exports.installSync = (cwd) => {
  return new Promise((resolve, reject) => {
    exports.spawnSync('yarn', ['install'], { cwd }).then(resolve).catch(() => {
      exports.spawnSync('npm', ['install', '--registry=https://registry.npm.taobao.org'], {
        cwd
      }).then(resolve).catch(reject)
    })
  })
}